﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
using System.IO;

namespace hxweditor
{
    public class MD5BuildEditor : BaseEditorWindow<MD5BuildEditor>
    {

        private string targetPathKey = "MD5BuildEditor_targetPath";
        private string targetPath = "";

        private string outputPathKey = "MD5BuildEditor_outputPath";
        private string outputPath = "";

        MD5BuildEditor()
		{
			this.titleContent = new GUIContent("MD5生成工具");
		}

        void OnEnable()
        {
            targetPath = PlayerPrefs.GetString(targetPathKey,"");
            outputPath = PlayerPrefs.GetString(outputPathKey, "");
        }

        void OnDisable()
        {
            PlayerPrefs.SetString(targetPathKey, targetPath);
            PlayerPrefs.SetString(outputPathKey, outputPath);
        }

        void OnGUI(){

            targetPath = ShowInputString("资源目录:", targetPath);
			if (ShowButton ("打开资源目录")) {
				FileTool.OpenFolderAndSelectFile (targetPath);
			}

            //ShowSpaceLine(1);

            //outputPath = ShowInputString("输出目录:",outputPath);
            //if (ShowButton ("打开输出目录")) {
            //    FileTool.OpenFolderAndSelectFile (outputPath);
            //}

            ShowSpaceLine(1);

            if (ShowButton("生成MD5关联"))
            {
                BuildMD5();
            }
            ShowSpaceLine(1);

            //if (ShowButton("拷贝文件到输出目录(CDN目录)"))
            //{
            //    Copy();
            //}

        }

        private void BuildMD5()
        {
			//拿到除了.meta文件之外的所有文件
			List<string> fileList = FileTool.GetAllFile(targetPath,new List<string>{".meta"});
			string targetName = FileTool.GetFileName(targetPath);
            string content = "";
            foreach (string file in fileList)
            {
				string fileName = FileTool.GetFileName (file);
				if (fileName == "CDNCONFIG")
					continue;
                if (content != "")
                    content += "\n";
				content += PathTool.RemoveTo1(file, targetName + "/");
                content += "|";
				content += FileTool.GetMD5HashFromFile (file);
            }
			if (content != "") {
				FileTool.WriteFile (targetPath + "/CDNCONFIG.txt",content);
				ShowAlert ("生成Md5列表完成");
			}
        }

        private void Copy()
        {
			List<string> fileList = FileTool.GetAllFile(targetPath,new List<string>{".meta"});
			foreach (string file in fileList) {
				string filePath = PathTool.RemoveTo1 (file, FileTool.GetFileName(targetPath));

				string strSource = PathTool.FormationPath (file);
				string strDestination = PathTool.FormationPath(outputPath + "/" + filePath);

				string strPath = Path.GetDirectoryName(strDestination);
				if (!Directory.Exists(strPath))
				{
					Directory.CreateDirectory(strPath);
				}
				File.Copy(strSource, strDestination,true);
			}
			ShowAlert ("拷贝完成");
        }

    }

}